import { getModule, Module, Mutation, VuexModule } from 'vuex-module-decorators';
// eslint-disable-next-line no-unused-vars
import { IMenuListItem } from '@/layout/layout-menu-list';
import store from '../index';
import { getConfigItem } from '@/utils/tools';

const HomePage = getConfigItem('HOME_PAGE');

export interface ITagView {
    title?: string;
    path?: string;
    fullPath?: string;
}

export interface ITagsViewState {
    active: string;
    visitedViews: ITagView[];
    menuList: IMenuListItem[];
}

// // 默认页面
// const defaultVisitedViews: ITagView = {
//     title: '首页',
//     path: HomePage,
// };

@Module({ dynamic: true, name: 'tagsView', namespaced: true, store })
class TagsViewStore extends VuexModule {
    public active: string = HomePage;
    public menuList: IMenuListItem[] = [];
    public visitedViews: ITagView[] = [];

    /**
     * 更新所有目录列表
     * @param menuList 目录列表
     */
    @Mutation
    updateMenuList(menuList: IMenuListItem[]): void {
        this.menuList = menuList;
    }

    /**
     * 获取所有目录列表
     * @return 目录列表
     */
    get queryMenuList(): IMenuListItem[] {
        return this.menuList;
    }

    /**
     * 更新当前激活地址
     * @param path 激活地址
     */
    @Mutation
    updateActive(path: string): void {
        this.active = path;
    }

    /**
     * 获取当前激活地址
     */
    get getActive(): string {
        return this.active;
    }

    /**
     * 添加新的标签页，也可用于激活标签
     * @param view
     */
    @Mutation
    insertVisitedView(path: string): void {
        // 1. 搜索地址是否存在，存在就跳过，并激活，不存在则添加，并激活
        const isExist = this.visitedViews.some(item => item.path === path);
        this.active = path;
        // 不存在, 并且不是首页，就添加添加标签
        if (!isExist && path !== HomePage) {
            const filterData = this.menuList.filter(item => item.menuUrl === path);
            const temp = filterData.length ? filterData[0] : { resourceName: '404', menuUrl: path };
            const title = temp.resourceName || '404';
            this.visitedViews.push({ title, path });
        }
    }

    /**
     * 直接添加新的标签页，不进行任何判断
     * 用于初始化
     * @param pathInfo 添加页面信息
     * @param isActive 是否激活添加标签，默认否
     */
    @Mutation
    addedDirectlyVisitedView(info: { pathInfo: ITagView; isActive?: boolean }): void {
        this.visitedViews.push(info.pathInfo);
        if (info.isActive) {
            this.active = info.pathInfo.path;
        }
    }

    /**
     * 删除当前标签页
     * @param info
     */
    @Mutation
    removeVisitedView(info: { path: string; index: number }): void {
        if (info.path === '/system/notice') {
            sessionStorage.removeItem('warnning-notice-treeKey');
        }

        let isDelActivePath = false;
        if (info.path === this.active) {
            isDelActivePath = true;
        }
        const visitedViews = [...this.visitedViews];
        visitedViews.splice(info.index, 1);
        this.visitedViews = visitedViews;
        // 如果删除的页面是激活页，重新激活当前页面
        if (!isDelActivePath) {
            return;
        }
        if (this.visitedViews.length) {
            this.active = this.visitedViews[this.visitedViews.length - 1].path;
        } else {
            this.active = HomePage;
        }
        console.log('关闭标签页:', info.path);
    }

    /**
     * 删除左边标签页
     * @param url
     */
    @Mutation
    removeLeftVisitedView(info: { path: string; index: number }): void {
        this.visitedViews = this.visitedViews.filter((_, index) => index >= info.index);

        // 如果删除的页面是激活页，重新激活当前页面
        const isDelActivePath = this.visitedViews.every(item => item.path !== this.active);
        if (!isDelActivePath) {
            return;
        }
        if (this.visitedViews.length) {
            this.active = this.visitedViews[this.visitedViews.length - 1].path;
        } else {
            this.active = HomePage;
        }
    }

    /**
     * 删除右边标签页
     * @param url
     */
    @Mutation
    removeRightVisitedView(info: { path: string; index: number }): void {
        this.visitedViews = this.visitedViews.filter((_, index) => index <= info.index);

        // 如果删除的页面是激活页，重新激活当前页面
        const isDelActivePath = this.visitedViews.every(item => item.path !== this.active);
        if (!isDelActivePath) {
            return;
        }
        if (this.visitedViews.length) {
            this.active = this.visitedViews[this.visitedViews.length - 1].path;
        } else {
            this.active = HomePage;
        }
    }

    /**
     * 在新窗口打开页面
     * @param path 新打开的地址
     * @param title 新打开的页面名
     */
    @Mutation
    openNewPage(info: { path: string; title: string }): void {
        window.open(`/#/?newpage=${info.path}&newtitle=${info.title}`, '_blank');
    }

    /**
     * 刷新页面
     * @param path 刷新页面的地址
     */
    @Mutation
    refreshPage(path: string): void {
        const iframe = document.querySelector(`.iframe-ctx[name="${path}"]`) as HTMLIFrameElement;
        if (iframe) {
            try {
                iframe.contentWindow.location.reload();
            } catch (e) {
                const temp = iframe.getAttribute('src');
                iframe.setAttribute('src', '');
                setTimeout(() => {
                    iframe.setAttribute('src', temp);
                }, 1000);
            }
        }
    }

    /**
     * 获取所有标签列表
     * @return visitedViews 列表
     */
    get queryVisitedViews(): ITagView[] {
        return this.visitedViews;
    }

    /**
     * 退出清空所有数据
     */
    @Mutation
    logout() {
        this.active = HomePage;
        this.menuList = [];
        this.visitedViews = [];
    }
}

export const TagsViewModule = getModule(TagsViewStore);
